<template>
  <div class="product-review">
    <!-- 顶部通知栏 -->
    <div class="topbar">
      限时优惠：全场咖啡豆满200元减30元 | 新用户注册立享85折
      <a href="#">立即查看</a>
    </div>

    <!-- 头部导航 -->

    <!-- 面包屑 -->
    <div class="breadcrumb">
      <div class="container">
        <router-link to="/" class="link">首页</router-link>
        <span class="sep">/</span>
        <router-link to="/all-coffees" class="link">全部咖啡豆</router-link>
        <span class="sep">/</span>
        <router-link :to="'/merchandiseproductdetail?id=' +product.id" class="link">{{ product.name }}</router-link>
        <span class="sep">/</span>
        <span>商品评价</span>
      </div>
    </div>

    <main class="main">
      <div class="container">
        <!-- 商品简要信息 -->
        <section class="product-info">
      <!-- 商品图片 -->
      <img
        :src="productImage"
        alt="商品图"
        :title="product.name"
      />

      <!-- 商品信息 -->
      <div>
        <h2>{{ product.name || '加载中...' }}</h2>
        <div class="stars">
          <i v-for="s in 5" :key="s" :class="s <= 4 ? 'fa fa-star' : 'fa fa-star-half-o'" />
          <span>4.7 ({{ product.view_count || 0 }}条评价)</span>
        </div>
        <p>{{ product.flavor_notes || '暂无风味描述' }}</p>
      </div>

      <!-- 返回详情页链接 -->
      <router-link
        :to="'/merchandiseproductdetail?id=' + product.id"
        class="back-link"
      >
        返回商品详情
      </router-link>
    </section>

        <div class="layout">
          <!-- 左侧评分统计 -->
          <aside class="stats">
            <h3>评分统计</h3>

            <!-- 总评分 -->
            <div class="total-score">
              <div class="score">4.7</div>
              <div class="stars">
                <i v-for="s in 5" :key="s" :class="s <= 4 ? 'fa fa-star' : 'fa fa-star-half-o'" />
              </div>
              <p>基于 126 条评价</p>
            </div>

            <!-- 星级分布 -->
            <div class="star-bar" v-for="(item, idx) in starDist" :key="idx">
              <span>{{ item.star }} 星</span>
              <div class="bar">
                <div class="fill" :style="{ width: item.percent + '%' }"></div>
              </div>
              <span>{{ item.percent }}%</span>
            </div>

            <!-- 标签 -->
            <div class="tags">
              <h4>用户常用标签</h4>
              <span v-for="tag in tags" :key="tag" class="tag">{{ tag }}</span>
            </div>
          </aside>

          <!-- 右侧评价区 -->
          <section class="review-area">
            <!-- 评价列表 -->
            <div class="review-list">
              <div class="review-header">
                <h3>用户评价 ({{ reviews.length }})</h3>
              </div>
            </div>
              <!-- 单条评价 -->
              <div class="tab-pane">
              <div class="reviews">
                <div class="summary">
                </div>
                <div class="review-list">
                  <div v-for="review in reviews" :key="review.id" class="review-card">
                  <div class="rating">{{ review.rating }}星</div>
                  <div class="content">{{ review.content }}</div>
                  <div class="meta">
                    <span>{{ formatDate(review.created_at) }}</span>
                  </div>
                 </div>
                  <div class="show-all-container" style="text-align: center; margin-top: 1rem;">

        </div>
              </div>
            </div>


              <!-- 分页 -->
              <div class="pagination">
  <a
    @click.prevent="prevPage"
    :class="{ 'disabled': currentPage === 1 }"
  >
    <i class="fa fa-chevron-left" />
  </a>

  <!-- 显示首页 -->
  <a
    @click.prevent="goToPage(1)"
    :class="{ 'active': currentPage === 1 }"
    v-if="currentPage > 3"
  >
    1
  </a>

  <!-- 显示当前页附近的页码 -->
  <a
    @click.prevent="goToPage(page)"
    :class="{ 'active': currentPage === page }"
    v-for="page in visiblePages"
    :key="page"
  >
    {{ page }}
  </a>

  <!-- 显示末页 -->
  <a
    @click.prevent="goToPage(totalPages)"
    :class="{ 'active': currentPage === totalPages }"
    v-if="currentPage < totalPages - 2"
  >
    {{ totalPages }}
  </a>

  <a
    @click.prevent="nextPage"
    :class="{ 'disabled': currentPage === totalPages }"
  >
    <i class="fa fa-chevron-right" />
  </a>
</div>
            </div>
          </section>
        </div>
      </div>
    </main>

    <!-- 返回顶部 -->
    <transition name="fade">
      <button v-show="showTop" class="back-top" @click="toTop">
        <i class="fa fa-arrow-up" />
      </button>
    </transition>

    <!-- 成功提示 -->
    <transition name="fade">
      <div v-show="showToast" class="toast">
        <i class="fa fa-check-circle" />
        评价提交成功，感谢您的反馈！
      </div>
    </transition>

    <!-- 底部 -->
    <Footer />
  </div>
</template>

<script>
  import api from '@/api/request'
export default {
  name: 'MerchandiseReview',
  data() {
    return {
      showTop: false,
      showToast: false,
      rating: 0,
      content: '',
      previews: [],
      currentPage: 1,
      totalPages: 0,
      totalReviews: 0,
      pageSize: 3,
      activeFilter: 0,
      sort: 'latest',
      filters: ['全部评价', '5 星', '4 星', '3 星', '2 星以下', '有图评价'],
      tags: ['花香明显', '酸度适中', '回甘好', '性价比高', '新鲜度好', '风味独特', '适合手冲', '包装精美'],
      starDist: [
        { star: 5, percent: 75 },
        { star: 4, percent: 15 },
        { star: 3, percent: 7 },
        { star: 2, percent: 2 },
        { star: 1, percent: 1 }
      ],
      product: {},
      reviews: [],
      productType: 'merchandise',
      productImage: '', // 默认占位图
    };
  },
  mounted() {
    window.addEventListener('scroll', this.handleScroll);
    // 组件挂载时加载第一页数据
    this.loadReviews(this.product.id);
  },
  beforeDestroy() {
    window.removeEventListener('scroll', this.handleScroll);
  },
  created() {
    const productId = this.$route.params.id;
    if (!productId || isNaN(Number(productId))) {
      // 可结合项目UI组件库添加用户提示（如Element UI的$message）
      this.$message?.error('商品ID不合法，请返回重试');
      this.$router.push('/merchandise'); // 跳回咖啡周边列表页
      return;
    }
    // 传入数字类型的ID（避免后端接收字符串ID报错）
    this.fetchProductInfo(Number(productId));

    this.loadReviews(Number(productId))

  },
    computed: {
  visiblePages() {
    const pages = [];
    const maxVisible = 5; // 最多显示5个页码

    // 计算显示范围
    let startPage = Math.max(1, this.currentPage - 2);
    let endPage = Math.min(this.totalPages, startPage + maxVisible - 1);

    // 调整起始页，确保显示足够的页码
    if (endPage - startPage < maxVisible - 1) {
      startPage = Math.max(1, endPage - maxVisible + 1);
    }

    // 生成页码数组
    for (let i = startPage; i <= endPage; i++) {
      pages.push(i);
    }

    return pages;
  }
},
  methods: {
        fetchProductInfo(id) {
      this.$axios.get(`http://127.0.0.1:8000/merchandiseProduct/${id}`)
        .then(res => {
          if (res && res.data) {
            this.product = res.data

            // 处理商品图片
            if (res.data.image_urls && res.data.image_urls.length > 0) {
              this.productImage = `http://127.0.0.1:8000/static/${res.data.image_urls[0]}`
            }
          }
        })
        .catch(err => {
          console.error('获取商品信息失败:', err)
        })
    },
    // 获取产品评论
    async loadReviews(id) {
    try {
      const response = await this.$axios.get(
        `http://127.0.0.1:8000/reviews/product/${id}`,
        {
          params: {
            product_type: this.productType,
            page: this.currentPage,
            limit: this.pageSize
          }
        }
      );

      this.reviews = response.data.reviews;
      this.totalReviews = response.data.pagination.total;
      this.totalPages = response.data.pagination.pages;
    } catch (err) {
      console.error('获取评论失败：', err);
    }
  },

  // 跳转到指定页
  goToPage(page) {
    if (page < 1 || page > this.totalPages) return;
    this.currentPage = page;
    this.loadReviews(this.product.id);
  },

  // 上一页
  prevPage() {
    if (this.currentPage > 1) {
      this.currentPage--;
      this.loadReviews(this.product.id);
    }
  },

  // 下一页
  nextPage() {
    if (this.currentPage < this.totalPages) {
      this.currentPage++;
      this.loadReviews(this.product.id);
    }
  },
    formatDate(dateString) {
      if (!dateString) return '无日期';
      const date = new Date(dateString);
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
    },
    handleScroll() {
      this.showTop = window.scrollY > 300;
    },
    toTop() {
      window.scrollTo({ top: 0, behavior: 'smooth' });
    },

  }
};
</script>

<style scoped>
:root {
  --primary: #8b5a2b;
  --dark: #3e2723;
  --light: #f5f5dc;
  --radius: 12px;
  --shadow: 0 2px 8px rgba(0,0,0,.06);
}
.product-review {
  min-height: 100vh;
  background: #f9fafb;
}
.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 1rem;
}
.topbar {
  background: var(--primary);
  color: #fff;
  text-align: center;
  padding: 0.5rem 0;
  font-size: 0.875rem;
}
.topbar a {
  text-decoration: underline;
  margin-left: 0.25rem;
}
.breadcrumb {
  background: #fff;
  border-bottom: 1px solid #e5e7eb;
  font-size: 14px;
  color: #6b7280;
  padding: 12px 0;
}
.breadcrumb a:hover {
  color: var(--primary);
}
.main {
  padding: 2rem 0;
}
.product-info {
  background: #fff;
  border-radius: var(--radius);
  box-shadow: var(--shadow);
  padding: 1.5rem;
  display: flex;
  flex-direction: column;
  gap: 1rem;
  margin-bottom: 2rem;
}
@media (min-width: 768px) {
  .product-info {
    flex-direction: row;
    align-items: center;
  }
}
.product-info img {
  width: 6rem;
  height: 6rem;
  object-fit: cover;
  border-radius: 0.5rem;
}
.product-info h2 {
  font-size: 1.25rem;
  font-weight: 700;
  color: #111;
}
.product-info .stars {
  color: var(--primary);
  font-size: 0.875rem;
  margin: 0.25rem 0;
}
.product-info .stars span {
  margin-left: 0.5rem;
  color: #6b7280;
}
.product-info p {
  font-size: 0.875rem;
  color: #6b7280;
}
.back-link {
  color: var(--primary);
  font-weight: 600;
}
.layout {
  display: grid;
  gap: 2rem;
  grid-template-columns: 1fr;
}
@media (min-width: 1024px) {
  .layout {
    grid-template-columns: 1fr 2fr;
  }
}
.stats, .review-area {
  background: #fff;
  border-radius: var(--radius);
  box-shadow: var(--shadow);
  padding: 1.5rem;
}
.stats {
  position: sticky;
  top: 6rem;
}
.stats h3, .review-area h3 {
  font-size: 1.125rem;
  font-weight: 700;
  margin-bottom: 1rem;
  color: #111;
}
.total-score {
  text-align: center;
  margin-bottom: 2rem;
}
.total-score .score {
  font-size: 2.25rem;
  font-weight: 700;
  color: #111;
}
.total-score .stars {
  color: var(--primary);
  margin: 0.5rem 0;
  font-size: 1.125rem;
}
.star-bar {
  display: flex;
  align-items: center;
  font-size: 0.875rem;
  margin-bottom: 0.5rem;
}
.star-bar span:first-child {
  width: 3.5rem;
  color: #6b7280;
}
.bar {
  flex: 1;
  height: 0.5rem;
  background: #e5e7eb;
  border-radius: 9999px;
  margin: 0 0.5rem;
  overflow: hidden;
}
.fill {
  height: 100%;
  background: var(--primary);
  border-radius: 9999px;
}
.tags {
  margin-top: 2rem;
}
.tags h4 {
  font-size: 0.875rem;
  font-weight: 600;
  margin-bottom: 0.5rem;
  color: #374151;
}
.tag {
  background: var(--light);
  color: var(--primary);
  font-size: 0.75rem;
  padding: 0.25rem 0.75rem;
  border-radius: 9999px;
  margin: 0.125rem;
  display: inline-block;
}
.filter-bar {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
  margin-bottom: 1.5rem;
}
.filter-bar button {
  padding: 0.5rem 1rem;
  border-radius: 0.5rem;
  font-size: 0.875rem;
  background: #fff;
  border: 1px solid #e5e7eb;
  color: #374151;
}
.filter-bar button.active,
.filter-bar button:hover {
  background: var(--primary);
  color: #fff;
}
.review-form {
  margin-bottom: 2rem;
}
.field {
  margin-bottom: 1rem;
}
.field label {
  display: block;
  font-size: 0.875rem;
  font-weight: 600;
  margin-bottom: 0.25rem;
  color: #374151;
}
.star-input {
  font-size: 1.5rem;
  color: var(--primary);
  cursor: pointer;
}
textarea {
  width: 100%;
  resize: vertical;
  padding: 0.75rem;
  border: 1px solid #d1d5db;
  border-radius: 0.5rem;
}
small {
  color: #6b7280;
}
.upload-box {
  display: block;
  border: 2px dashed #d1d5db;
  border-radius: 0.5rem;
  padding: 1.5rem;
  text-align: center;
  cursor: pointer;
  transition: border-color 0.3s;
}
.upload-box:hover {
  border-color: var(--primary);
}
.upload-box i {
  font-size: 1.5rem;
  color: #9ca3af;
  margin-bottom: 0.5rem;
}
.upload-box span {
  font-size: 0.875rem;
  color: #6b7280;
}
.preview {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
  margin-top: 0.5rem;
}
.img-wrap {
  position: relative;
}
.img-wrap img {
  width: 5rem;
  height: 5rem;
  object-fit: cover;
  border-radius: 0.375rem;
}
.img-wrap i {
  position: absolute;
  top: -0.375rem;
  right: -0.375rem;
  background: #fff;
  border-radius: 50%;
  width: 1.25rem;
  height: 1.25rem;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 0.625rem;
  color: #6b7280;
  cursor: pointer;
}
.submit-btn {
  background: var(--primary);
  color: #fff;
  padding: 0.5rem 1.25rem;
  border-radius: 0.5rem;
  font-weight: 600;
}
.submit-btn:hover {
  background: var(--dark);
}
.review-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}
.review-header select {
  padding: 0.375rem 0.75rem;
  border-radius: 0.375rem;
  border: 1px solid #d1d5db;
}
.review-card {
  background: #fff;
  border-radius: var(--radius);
  box-shadow: var(--shadow);
  padding: 1.5rem;
  margin-bottom: 1.5rem;
}
.user {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  margin-bottom: 0.75rem;
}
.user img {
  width: 2.5rem;
  height: 2.5rem;
  border-radius: 50%;
}
.user h4 {
  font-weight: 600;
  font-size: 0.875rem;
}
.user small {
  font-size: 0.75rem;
  color: #6b7280;
}
.user .date {
  margin-left: auto;
  font-size: 0.75rem;
  color: #6b7280;
}
.review-card .stars {
  color: var(--primary);
  font-size: 0.875rem;
  margin-bottom: 0.5rem;
}
.text {
  color: #374151;
  line-height: 1.5;
}
.pics {
  display: flex;
  gap: 0.5rem;
  flex-wrap: wrap;
  margin: 0.75rem 0;
}
.pics img {
  width: 5rem;
  height: 5rem;
  object-fit: cover;
  border-radius: 0.375rem;
}
.actions {
  display: flex;
  gap: 1.5rem;
  font-size: 0.875rem;
  color: #6b7280;
  cursor: pointer;
}
.actions span:hover {
  color: var(--primary);
}
.reply {
  margin-top: 0.75rem;
  padding: 0.75rem;
  background: #f9fafb;
  border-radius: 0.5rem;
  font-size: 0.875rem;
  color: #374151;
}
.pagination {
  display: flex;
  justify-content: center;
  gap: 0.5rem;
  margin-top: 2rem;
}
.pagination a,
.pagination span {
  padding: 0.375rem 0.75rem;
  border: 1px solid #e5e7eb;
  border-radius: 0.375rem;
  font-size: 0.875rem;
  color: #6b7280;
}
.pagination a.active,
.pagination a:hover {
  background: var(--primary);
  color: #fff;
}
.pagination .disabled {
  cursor: not-allowed;
  opacity: 0.5;
}
.back-top {
  position: fixed;
  right: 1.5rem;
  bottom: 1.5rem;
  width: 3rem;
  height: 3rem;
  background: var(--primary);
  color: #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.25rem;
  box-shadow: var(--shadow);
  z-index: 50;
}
.toast {
  position: fixed;
  top: 5rem;
  right: 1.5rem;
  background: #10b981;
  color: #fff;
  padding: 0.75rem 1.25rem;
  border-radius: 0.5rem;
  font-size: 0.875rem;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  z-index: 50;
}
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s;
}
.fade-enter,
.fade-leave-to {
  opacity: 0;
}


/* 评论列表容器 */
.review-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 单条评论卡片 */
.review-card {
  background-color: #f9f9f9;
  padding: 15px;
  border-radius: 6px;
  border-left: 4px solid #ff9500;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  transition: transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out;
}

.review-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

/* 评论星级 */
.rating {
  font-size: 16px;
  font-weight: bold;
  color: #ff9500;
  margin-bottom: 8px;
}

/* 评论内容 */
.content {
  font-size: 14px;
  line-height: 1.6;
  color: #333;
  margin-bottom: 8px;
}

/* 评论元信息（日期等） */
.meta {
  font-size: 12px;
  color: #999;
}
</style>